<?php
/**
 * Created by PhpStorm.
 * User: krystal
 * Date: 2019/2/28
 * Time: 19:40
 */

namespace app\common\model;

use think\Cache;

/**
 * 课程章节进度模型
 * Class ZhunleCourseSection
 * @package app\common\model
 */
class ZhunleCourseSectionProgress extends Base
{
    protected $table = 'wechat_backup_07_18_14_43_00.zhunle_course_section_progress';

    const ALL_COURSE_SECTION_IDS = ':user:course:section:progress';
    const UID_COURSE_SECTION_PROGRESS_INFO = ':user:course:section:progress:info:';
    const CACHE_TIME = 86400 * 7;

    /**
     * 删除用户章节进度缓存
     * @param array $map
     * @return bool
     */
    public function rm_cache($map = [])
    {
        $uid = $map['uid'];
        $csid = $map['csid'];

        Cache::rm($uid . self::ALL_COURSE_SECTION_IDS);
        Cache::rm($uid . self::UID_COURSE_SECTION_PROGRESS_INFO . $csid);

        return true;
    }

    /**
     * 保存用户的播放进度
     * @param array $map
     * @return bool
     */
    public function saveProgress($map = [])
    {
        $uid = $map['uid'];
        $csid = $map['csid'];
        $progress = $map['progress'];

        //查询当前章节的进度信息
        $section_progress = $this->getSectionProgressInfo(['id' => $csid, 'uid' => $uid]);

        //如果保存过进度,就更新
        if ($section_progress)
        {
            if ($section_progress['total_progress'] < $progress)
            {
                $arr = [
                    'total_progress' => $progress,
                    'recent_progress' => $progress,
                ];
            } else
            {
                $arr = [
                    'recent_progress' => $progress,
                ];
            }

            try
            {
                $where = [
                    'csid' => $csid,
                    'uid' => $uid
                ];

//                $this->where($where)->update($arr);

                self::update($arr, $where);

                $this->rm_cache(['uid' => $uid, 'csid' => $csid]);

            }
            catch (\Exception $e)
            {
                $this->error = '保存用户进度失败';
                return false;
            }

        }//如果没有保存就添加
        else
        {
            try
            {
                $arr = [
                    'uid' => $uid,
                    'csid' => $csid,
                    'total_progress' => $progress,
                    'recent_progress' => $progress,
                ];

                $this->save($arr);

                $this->rm_cache(['uid' => $uid, 'csid' => $csid]);
            }
            catch (\Exception $e)
            {
                $this->error = '保存用户进度失败';
                return false;
            }
        }

        return true;
    }

    /**
     * 获取某个用户的已看的章节id
     * @param array $map
     * @return array|bool
     */
    public function getUidCourseSectionProgress($map = [])
    {
        $uid = $map['uid'];

        $all_course_section_ids = false;

        $data_list = [];

        if ($this->cache_on >= 1)
        {
            $all_course_section_ids = Cache::get($uid . self::ALL_COURSE_SECTION_IDS);
        }

        if ($all_course_section_ids === false)
        {
            $where = ['uid' => $uid];
            try
            {
                $data = $this
                    ->where($where)
                    ->column('csid');
                // 将课程章节id组成字符串
                if ($data)
                {
                    $all_course_section_ids = implode(',', $data);
                } else
                {
                    $all_course_section_ids = '';
                }

                // 缓存课程章节id,根据课程id
                if ($all_course_section_ids && $this->cache_on >= 1)
                {
                    Cache::set($uid . self::ALL_COURSE_SECTION_IDS, $all_course_section_ids, self::CACHE_TIME);
                }
            }
            catch (\Exception $e)
            {
                $this->error = '获取章节进度信息失败.';
                return false;
            }
        }

        if ($all_course_section_ids)
        {
            // 将课程章节id转为数组
            $all_course_section_id = explode(',', $all_course_section_ids);
        } else
        {
            $all_course_section_id = [];
        }

        // 根据当前页课程章节id获取所需的课程章节信息
        if (!empty($all_course_section_id))
        {
            $ac_ids = '';
            $temp = [];

            // 获取缓存的课程章节内容,根据课程章节id
            foreach ($all_course_section_id as $ac_id)
            {
                if ($this->cache_on >= 1)
                {
                    // 根据课程章节id 获取课程章节内容
                    $temp[$ac_id] = Cache::get($uid . self::UID_COURSE_SECTION_PROGRESS_INFO . $ac_id);
                } else
                {
                    // 缓存未开启时，默认从数据库获取
                    $temp[$ac_id] = false;
                }
                // 课程章节内容未缓存，等待从数据库中获取
                if ($temp[$ac_id] === false && $ac_id)
                {
                    $ac_ids .= $ac_id . ',';
                }
            }

            // 从数据库获取课程章节内容
            if ($ac_ids != '' || strlen($ac_ids) > 0)
            {
                //去掉结尾的 ，
                $ac_ids = substr($ac_ids, 0, strlen($ac_ids) - 1);

                $where = ['uid' => $uid];

                try
                {
                    $data = $this
                        ->field('csid,total_progress,recent_progress')
                        ->where($where)
                        ->where('csid in(' . $ac_ids . ')')
                        ->select();

                    $course = json_decode(json_encode($data, true), true);
                }
                catch (\Exception $e)
                {
                    $this->error = '获取章节详情信息失败.';
                    return false;
                }

                if (!empty($course))
                {
                    foreach ($course as $c)
                    {
                        // 将课程章节内容缓存
                        if ($this->cache_on >= 1)
                        {
                            Cache::set($uid . self::UID_COURSE_SECTION_PROGRESS_INFO . $c['csid'], $c, self::CACHE_TIME);
                        }
                        // 将数据库查出来的内容 写入到数组中为空的部分
                        if ($c)
                        {
                            $temp[$c['csid']] = $c;
                        }
                    }
                }
            }

            foreach ($temp as $item)
            {
                if ($item)
                {
                    $data_list[] = $item;
                }
            }
        }

        return $data_list;
    }

    /**
     * 获取当前用户当前章节的进度
     * @param array $map
     * @return array|bool
     */
    public function getSectionProgressInfo($map = [])
    {
        $id = $map['id'];
        $uid = $map['uid'];

        $data = false;

        if ($this->cache_on >= 1)
        {
            $data = Cache::get($uid . self::UID_COURSE_SECTION_PROGRESS_INFO . $id);
        }

        if ($data === false)
        {
            $where = ['uid' => $uid, 'csid' => $id];
            try
            {
                $data = $this
                    ->field('csid,total_progress,recent_progress')
                    ->where($where)
                    ->findOrFail();
                $data = json_decode(json_encode($data, true), true);
            }
            catch (\Exception $e)
            {
                $data = [];
            }

            if ($this->cache_on >= 1)
            {
                Cache::set($uid . self::UID_COURSE_SECTION_PROGRESS_INFO . $id, $data, self::CACHE_TIME);
            }
        }
        return $data;
    }

}
